package com.vilen.learn;

/**
 * Created by Administrator on 2016/1/25.
 */
public class Hangman {
    private String solution;
    private String used = "AEIOU";
    private String problem;
    private boolean matched;
    private int tries = 12;

    public void start(String solution) {

        this.solution = solution;
        generateProblem();
        tryVowel();
    }

    private void generateProblem() {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < solution.length(); i++) {
            stringBuffer.append("_");
        }
        problem = stringBuffer.toString();
    }

    private void tryVowel() {
        char[] chars = "AEIOU".toCharArray();
        for (int i = 0; i < chars.length; i++) {
            replaceProblem(chars[i]);
        }
    }

    public int tries() {
        return tries;
    }

    public int length() {
        return solution.length();
    }

    public String used() {
        return used;
    }

    public String problem() {
        return problem;
    }

    public boolean tryChar(char ch) {
        replaceProblem(ch);
        used += ch;
        if(!matched) {
            tries--;
        }
        return matched;
    }

    private void replaceProblem(char ch) {
        matched = false;
        char[] problemChars = problem.toCharArray();
        char[] chars = solution.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ch) {
                problemChars[i] = ch;
                matched = true;
            }
        }
        problem = String.valueOf(problemChars);
    }

    public boolean hasWon() {

        return problem.equals(solution);
    }

    public boolean gameOver() {

        return (tries == 0);
    }

    public String getSolution() {
        return solution;
    }
}
